const Router = require('koa-router')
const { getConf } = require('../config/config')
const service = require('../service/service')
const { Task } = require('../db')
const fs = require('fs')
const zlib = require('zlib')
const log4js = require('../config/log4js')
const log = log4js.getLogger()

const route = new Router({
  // prefix: getConf('api:prefix') || '/api'
})

route.get('ESearchBook', '/e/book/:key', async ctx => {
  const res = await service.getSearchList(ctx.params.key)
  ctx.body = res.data
})

  .post('EAddBookTask', '/e/task', async ctx => {
    const { bid, cover, title, author } = ctx.request.body
    const task = new Task({
      bid,
      cover,
      title,
      author,
      userid: ctx.user.id
    })

    await task.save().then(() => {
      ctx.body = 'success'
    }).catch(err => {
      ctx.throw(err)
    })
  })

  .get('EBookTaskList', '/e/task', async ctx => {
    const taskList = await Task.find({
      userid: ctx.user.id
    })
    ctx.body = taskList
  })

  .delete('EBookTask', '/e/task/:id', async ctx => {
    await Task.deleteOne({
      id: ctx.params.id
    })
    ctx.body = 'success'
  })

  .get('LBookList', '/l/book', async ctx => {
    const files = fs.readdirSync('book')
    ctx.body = files
  })

  .get('LBookDownload', '/l/book/:name', async ctx => {
    const buf = fs.readFileSync(`book/${ctx.params.name}`)
    // ctx.response.type =
    ctx.body = buf
  })

  .get('LGetAllUids', '/l/uids', async ctx => {
    ctx.body = getConf('uids')
  })

  .get('LGetAllBooksByUid', '/l/book/:uid/uid', async ctx => {
    let res = null
    let i = 0
    const max = 12
    while (!res && i++ < max) {
      res = await service.getEBookList(ctx.params.uid).catch(err => {
        log.error(`request for getAllBooksByUid error ${i}`)
        log.error(err)
      })
    }
    ctx.body = res.data
  })

  .delete('LDeleteBooksByUid', '/l/book/:uid/uid', async ctx => {
    const { bids } = ctx.request.query
    await service.deleteMyBooks(ctx.params.uid, bids)
    ctx.body = 'success'
  })

  .get('SGetAllLogs', '/s/logs', async ctx => {
    const ret = {}
    const logs = fs.readdirSync('./logs')
    for (const log of logs) {
      if (fs.lstatSync(`./logs/${log}`).isDirectory()) {
        ret[log] = fs.readdirSync(`./logs/${log}`)
      }
    }
    ctx.body = ret
  })

  .get('SGetLogByFileName', '/s/log', async ctx => {
    const name = ctx.query.name
    const buf = fs.readFileSync(`./logs/${name}`)
    if (name.endsWith('.log')) {
      ctx.body = buf.toString()
    } else if (name.endsWith('.gz')) {
      ctx.body = zlib.unzipSync(buf).toString()
    } else {
      ctx.throw('非法文件名')
    }
  })

module.exports = route
